<template>
  <div class="add-subitem-container">
    <h2>添加课程任务项</h2>
    <el-form 
      ref="subitemFormRef" 
      :model="subitemForm" 
      :rules="rules" 
      label-width="120px"
      class="subitem-form"
    >
      <el-form-item label="任务名称" prop="title">
        <el-input v-model="subitemForm.title" placeholder="请输入任务名称" maxlength="30" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="任务描述" prop="body">
        <el-input v-model="subitemForm.body" type="textarea" placeholder="请输入任务描述" :rows="4" maxlength="200" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="所属课程" prop="parentid">
        <el-select v-model="subitemForm.parentid" placeholder="请选择所属课程" clearable>
          <el-option 
            v-for="course in courses" 
            :key="course.id" 
            :label="course.title || course.name" 
            :value="course.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddSubitem',
  setup() {
    const userStore = useUserStore()
    const subitemForm = reactive({
      title: '',
      body: '',
      parentid: ''
    })
    
    const courses = ref([])
    const subitemFormRef = ref(null)
    
    const rules = {
      title: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      body: [
        { required: true, message: '请输入任务描述', trigger: 'blur' },
        { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
      ],
      parentid: [
        { required: true, message: '请选择所属课程', trigger: 'change' }
      ]
    }
    
    // 获取课程列表
    const fetchCourses = async () => {
      try {
        console.log('开始获取课程列表...');
        const response = await api.items.getAll(6);
        
        console.log('获取课程列表响应:', response);
        
        if (Array.isArray(response) && response.length > 0) {
          courses.value = response;
          console.log('成功获取课程列表:', courses.value);
        } else {
          courses.value = [];
          console.warn('课程列表为空');
          ElMessage.info('当前暂无课程，请先添加课程');
        }
      } catch (error) {
        console.error('获取课程列表失败:', error);
        ElMessage.error('获取课程列表失败，请稍后重试');
        courses.value = [];
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        // 验证表单
        await subitemFormRef.value.validate();
        
        // 检查登录状态
        if (!userStore.isAuthenticated) {
          ElMessage.error('请先登录');
          return;
        }
        
        // 检查用户ID
        if (!userStore.userInfo?.id) {
          console.error('无法获取用户ID:', userStore.userInfo);
          ElMessage.error('用户信息不完整，请重新登录');
          return;
        }
        
        // 检查是否选择了课程
        if (!subitemForm.parentid) {
          ElMessage.error('请选择所属课程');
          return;
        }
        
        // 准备提交数据 - 根据后端subitems表结构调整
        const submitData = {
          title: subitemForm.title,
          body: subitemForm.body,
          userid: userStore.userInfo.id,
          parentid: parseInt(subitemForm.parentid),
          parentType: '课程' // 根据实际数据改为中文
          // 注意：authorName字段在后端可能是自动生成的，不需要手动传递
        };
        
        console.log('准备提交的课程任务数据:', submitData);
        console.log('表索引: 7 (subitems表)');
        
        // 调用API添加课程任务项 - 使用与AddCourse.vue相同的逻辑
        const response = await api.items.add(submitData, 7);
        
        console.log('提交响应:', response);
        
        if (response && response.success !== false) {
          ElMessage.success('课程任务项添加成功！');
          resetForm();
        } else {
          ElMessage.error(response?.message || '课程任务项添加失败，请重试！');
        }
      } catch (error) {
        console.error('添加课程任务项失败:', error);
        // 使用与AddCourse.vue相同的错误处理逻辑
        if (error.response) {
          ElMessage.error(`提交失败: ${error.response.data?.message || error.response.statusText}`);
        } else if (error.message) {
          ElMessage.error(`提交失败: ${error.message}`);
        } else {
          ElMessage.error('提交失败，请检查网络连接！');
        }
      }
    };
    
    // 重置表单
    const resetForm = () => {
      const form = subitemFormRef.value;
      if (form) {
        form.resetFields();
      }
    }
    
    // 组件挂载时获取课程列表
    onMounted(() => {
      fetchCourses();
    })
    
    return {
      subitemForm,
      rules,
      courses,
      subitemFormRef,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.add-subitem-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 2rem;
}

.add-subitem-container h2 {
  font-size: 1.8rem;
  color: #333;
  margin-bottom: 1.5rem;
  text-align: center;
  padding-bottom: 1rem;
  border-bottom: 2px solid #42b983;
}

.subitem-form {
  margin-top: 1rem;
}

.el-form-item {
  margin-bottom: 1.5rem;
}

.el-form-item__content {
  line-height: 1;
}

.el-button {
  min-width: 80px;
}

.el-button + .el-button {
  margin-left: 10px;
}

@media (max-width: 768px) {
  .add-subitem-container {
    padding: 1.5rem;
    margin: 1rem;
  }
  
  .add-subitem-container h2 {
    font-size: 1.5rem;
  }
  
  .el-form-item__label {
    width: 100px;
  }
}
</style>